package com.demo.threadlocaldemo;

import java.util.concurrent.TimeUnit;

/**
 * @Created by xiangty on 2021/7/14
 * <p>
 * 初始值：initialValue()
 * 访问器：get/set;
 * 回收：remove
 */
public class ThreadLocalBasic {

    public static ThreadLocal<Long> x = new ThreadLocal<Long>() {
        // 初始值，没有get方法的话会initialValue方法不会触发。
        @Override
        protected Long initialValue() {
            System.out.println("initialValue...");
            return 100L;
        }
    };

    public static ThreadLocal<Long> xx = new ThreadLocal<Long>(){
        @Override
        protected Long initialValue() {
            System.out.println("xx --> initialValue...");
            return Thread.currentThread().getId();
        }
    };

    public static void main(String[] args) {
        // get获取值
//        System.out.println(x.get()); // 没有get方法的时候，initialValue不会加载

//        xx1();
//        xx2();
        xx3();

    }

    private static void xx1() {
        new Thread(()->{
            System.out.println(xx.get());
        }).start();
        System.out.println(xx.get());
        /*
            输出结果：
            xx --> initialValue...
            xx --> initialValue...
            1
            12
         */
    }

    private static void xx2() {
        new Thread(()->{
            System.out.println(xx.get());
        }).start();

        xx.set(100L);

        System.out.println(xx.get());
        /*
            输出结果：
            100
            xx --> initialValue...
            12
         */
    }

    private static void xx3() {
        new Thread(()->{
            System.out.println(xx.get());
        }).start();

        xx.set(100L);
        xx.remove();
        System.out.println(xx.get());
        /*
            输出结果：
            xx --> initialValue...
            xx --> initialValue...
            1
            12
         */
    }

}
